package com.ebelter.btlibrary.btble.ble.bluetooth.device.impl;


import android.os.SystemClock;

import com.ebelter.btlibrary.btble.ble.bluetooth.device.IBleServerWriter;
import com.ebelter.btlibrary.btble.ble.bluetooth.device.InternalChannel;
import com.ebelter.btlibrary.btble.ble.model.BtAck;
import com.ebelter.btlibrary.btble.ble.model.BtRequest;
import com.ebelter.btlibrary.util.ULog;

import java.util.Arrays;
import java.util.LinkedList;

/**
 * 蓝牙指令编辑者，抽象层，具体由开发者实现，用于蓝牙数据协议，编辑蓝牙指令
 * Created by Sergio Pan on 2017/11/28.
 */
public abstract class BleCommandEditor implements InternalChannel {

    protected final static String TAG = "BleCommandEditor";
    private IBleServerWriter mBleMessageWriter;
    private StringBuffer sb;
    /*** 请求队列 ***/
    private LinkedList<BtRequest> mRequests = new LinkedList<>();
    /*** 响应的ACK ***/
    private BtAck respAck;
    /*** 上一个请求的ACK ***/
    private BtAck preAck;
    /*** 停止线程 ***/
    private boolean isStop = false;
    protected byte dataHeaderSend;



    public void setDataHeaderSend(byte dataHeaderSend) {
        this.dataHeaderSend = dataHeaderSend;
    }

    public void registerBleMessageWriter(IBleServerWriter bleMessageWriter) {
        this.mBleMessageWriter = bleMessageWriter;
        new Thread(ackRun).start();
    }

    protected void sendBleMessage(byte[] data) {
        ULog.i(TAG, "------sendBleMessage-------data = " + Arrays.toString(data));
        if (mBleMessageWriter != null) {
            mBleMessageWriter.writeLlsAlertLevel(encrypt(data));
        }
    }

    @Override
    public void sendCommnd(Object command) {
        onReceiveCommand(command);
    }

    protected abstract void onReceiveCommand(Object command);

    /**
     * 加密处理，默认为不加密，如数据需要加密，需重写此方法
     * @param data
     * @return
     */
    protected byte[] encrypt(byte[] data){
        return data;
    }

    @Override
    public void updateRespondAck(BtAck ack) {
        this.respAck = ack;
    }

    public byte xor(byte[] bytes) {

        byte x = bytes[1];
        int len = bytes.length;
        for (int i = 2; i < len; i++) {
            x ^= bytes[i];
        }

        return x;
    }


//    protected String getArrayString(byte[] data) {
//        if (sb == null) {
//            sb = new StringBuffer();
//        }
//        sb.setLength(0);
//        int i = 0;
//        while (i < data.length) {
//            sb.append(Integer.toHexString(data[i] & 0xff)).append(" ");
//            i++;
//        }
//        if (sb.length() > 0) {
//            sb.deleteCharAt(sb.length() - 1);
//        }
//        return sb.toString();
//    }

    /**
     * 重发保障机制处理
     * 1.次数：最多3次
     * 2.间隔时间
     */
    private Runnable ackRun = new Runnable() {

        @Override
        public void run() {

            while (!isStop) {
                if (mRequests!=null&&mRequests.size()>0){

                    BtRequest request = mRequests.poll();
                    if (request != null && request.getData() != null) {
                        sendBleMessage(request.getData());
                        preAck = request.getAck();
                        SystemClock.sleep(1000);
                        // 上一次发送的ACK和接收响应ACK不相同，则重复一次
                        if (respAck != null) {
                            ULog.i("rrrrrr", "-----ackRun-----preAck = " + preAck.getAck() + ", respAck = " + respAck.getAck());
                        }
                        if (preAck.equals(respAck)) {
                            ULog.i("rrrrrr", "-----ackRun-----reSend-1--");
                            sendBleMessage(request.getData());
                            SystemClock.sleep(1000);
                            // 上一次发送的ACK和接收响应ACK不相同，第三次发送
                            if (preAck.equals(respAck)) {
                                ULog.i("rrrrrr", "-----ackRun-----reSend-2--");
                                sendBleMessage(request.getData());
                                SystemClock.sleep(1000);
                            }
                        }
                    }
                }

                SystemClock.sleep(200);
            }
        }
    };

    public void stop() {
        isStop = true;
    }

    /**
     * 发送请求，自带消息重发机制实现
     */
    protected synchronized void sendResquest(BtAck ack, byte[] bytes) {
        if(mRequests!=null){
            mRequests.add(new BtRequest(ack, bytes));
        }

    }

    public void release() {
        //停止线程
        isStop = true;
        if (mRequests != null) {
            mRequests.clear();
        }
    }


}
